<?php
class core extends wenyan {
	public $db;
	public $ezr; //分页
	public $tbp;
	public $smarty;
	public $domain;
	public $baidu_ak;
	public $act, $app;
	public $now, $ip;
	public $configs; //配置参数
	public $notify; //消息推送
	public $request;
	public $admin_id, $admin_name;

	public function __construct() {
		parent::__construct();
		global $db, $ezr, $tbp, $smarty, $domain, $baidu_ak, $act, $app;
		global $notify, $request;
		$this->db = $db;
		$this->ezr = $ezr;
		$this->tbp = $tbp;
		$this->smarty = $smarty;
		$this->domain = $domain;
		$this->baidu_ak = $baidu_ak;
		$this->app = $app;
		$this->act = $act;
		$this->now = time();
		$this->ip = ip();
		$this->request = $request;

		//加载配置参数
		$this->configs = array();
		$_config_sql = "SELECT name, memo, content FROM {$this->tbp}config";
		$_configs = $this->db->get_results($_config_sql);
		if ($_configs) {
			foreach ($_configs as $_config) {
				$this->configs[$_config->name] = $_config->content;
				if (stripos($_SERVER['SCRIPT_NAME'], '/api.php')===false){
					$this->smarty->assign($_config->name,$_config->content);
				}
			}
		}

		//消息推送
		$this->notify = $notify;
		
		if (in_array($act, array('login'))) {
			$this->admin_id = 0;
			$this->admin_name = '';
		} else {
			$this->check_login();
		}
		$this->_handle_log();
		//菜单
		$this->_menu();
	}

	//是否登录
	public function _check_login() {
		if (isset($_SESSION['admin']) && is_object($_SESSION['admin']) && isset($_SESSION['admin']->id) && intval($_SESSION['admin']->id)>0) {
			$this->admin_id = $_SESSION['admin']->id;
			$this->admin_name = $_SESSION['admin']->name;
			return true;
		} else {
			return false;
		}
	}

	//对是否登录函数的封装，如果登录了，则返回true，
	//否则，返回错误信息：-100，APP需检查此返回值，判断是否需要重新登录
	public function check_login(){
		if ($this->_check_login()) {
			return true;
		} else {
			//error('请登录', -100);
			$_SESSION['gourl'] = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];;
			header("Location: index.php?act=login");
		}
	}

	//显示
	public function display($tpl='', $element=array()) {
		global $json;
		if (stripos($_SERVER['SCRIPT_NAME'], '/api.php')!==false){
			$vars = $this->smarty->getTemplateVars();
			unset($vars['nav']);
			unset($vars['SCRIPT_NAME']);
			//unset($vars['page']);
			unset($vars['BRSR']);
			success($vars);
			exit;
		}
		if ($tpl) {
			$template_file = $tpl;
		} else {
			$template_file = "{$this->app}.{$this->act}.html";
			if (!file_exists(TEMPLATE_PATH . '/' . $template_file)) {
				error_tip('Template does not exists.');
			}
		}
		$this->smarty->assign("app", $this->app);
		$this->smarty->assign("act", $this->act);
		$this->smarty->assign('web_title', WEB_TITLE);
		if (is_array($element)) $this->smarty->assign($element);
		$this->smarty->assign($_GET);
		$this->smarty->assign($_POST);
		if (isset($_SESSION['admin']) && is_object($_SESSION['admin'])) {
			$sql = "SELECT * FROM {$this->tbp}admin WHERE id='".$_SESSION['admin']->id."'";
			$_SESSION['admin'] = $this->db->get_row($sql);
			$this->smarty->assign("admin", $_SESSION['admin']);
		}
		// if ($this->app=='home' || $this->act=='info' || $this->act=='password') {
		// 	$this->smarty->display($template_file);
		// } else {
		// 	$this->permission($this->admin_id, $this->app, $this->act);
		// 	$this->smarty->display($template_file);
		// }
		if ($this->app=='home' || $this->act=='info' || $this->act=='password') {
			$this->smarty->display($template_file);
		} else {
			$sql = "SELECT id FROM {$this->tbp}admin_permission WHERE 
				app='{$this->app}' AND (act='{$this->act}' OR act='*') AND admin_id = '{$this->admin_id}'";
			write_log($sql);
			//echo $sql;exit();
			$permission = $this->db->get_var($sql);
			// var_dump($permission);exit;
			if ($permission || $this->admin_id < 2) {
				$this->smarty->display($template_file);
			} else {
				error('你没有权限，请联系超级管理员！');
				$this->smarty->display('home.index.html');
			}
		}

		exit;
	}
	
	// //检测权限, app为全英文且act不为空即检测权限表, 否则检测菜单表(app使用菜单名), 为兼容权限表没有指定的app与act
	// public function permission($admin_id, $app, $act='') {
	// 	$count = 0;
	// 	if (is_en_cn($app)==0) {
	// 		$count = SQL::share('admin_permission')->where("app='{$app}' AND (act='{$act}' OR act='*') AND admin_id='{$admin_id}'")->count();
	// 	} else {
	// 		$menu_id = SQL::share('gm_menu')->where("name='{$app}'")->val('id');
	// 		$count = SQL::share('admin_menu')->where("menu_id='{$menu_id}' AND admin_id='{$admin_id}'")->count();
	// 	}
	// 	if ($count==0 && $admin_id!=1) error('你没有权限，请联系超级管理员！');
	// }

	//消息推送
	public function send_notify($message, $member_id=-1, $goto_target='') {
		$this->send_notify_sms($message, $member_id, '', 0, $goto_target);
	}
	//消息推送与短息，先保存到数据库，再发送
	public function send_notify_sms($message, $member_id=-1, $sms_content='', $template_id=0, $goto_target='') {
		global $sms_api_key;
		$mobile = $udid = '';
		if ($member_id>0) {
			$sql = "SELECT udid, mobile FROM {$this->tbp}member WHERE id='{$member_id}'";
			$member = $this->db->get_row($sql);
			if ($member) {
				$udid = $member->udid;
				$mobile = $member->mobile;
			}
		}
		//写入消息表
		$message_type = '';
		if (strpos($message, '商品')!==false) {
			$message_type = 'goods';
		} else if (strpos($message, '店铺')!==false) {
			$message_type = 'shop';
		} else if (strpos($message, '订单')!==false) {
			$message_type = 'order';
		} else {
			$message_type = 'html5';
		}
		$this->save_message($message, $member_id, $message_type, $goto_target);
		//发送推送
		if ($udid) $this->notify->send($udid, $message, '', '', array('type'=>'message'));
		//发送短信
		if ((is_array($sms_content) || strlen($sms_content)) && strlen($mobile)) {
			if (strlen($sms_api_key)) $sms_content = $message;
			$sms_id = $this->save_sms($mobile, $message);
			if (send_sms($mobile, $sms_content, $template_id)) $this->save_sms($mobile, $message, $sms_id);
		}
	}
	//操作消息表
	public function save_message($message, $member_id, $message_type='', $goto_target=''){
		if ($member_id>0) {
			$sql = "INSERT INTO {$this->tbp}message (member_id, content, add_time, readed, message_type, goto_target) VALUES
				('{$member_id}', '{$message}', '".time()."', '0', '{$message_type}', '{$goto_target}')";
			$this->db->query($sql);
		} else if ($member_id==0) {
			$sql = "SELECT id FROM {$this->tbp}member WHERE status=1 AND last_time>'".(time()-60*60*24*30)."'"; //一个月内登录过的才发送
			$members = $this->db->get_results($sql);
			if ($members) {
				$sql = "INSERT INTO {$this->tbp}message (member_id, content, add_time, readed, message_type, goto_target) VALUES ";
				foreach ($members as $k=>$g) {
					$sql .= "('{$g->id}', '{$message}', '".time()."', '0', '{$message_type}', '{$goto_target}'),";
				}
				$sql = trim($sql, ',');
				$this->db->query($sql);
			}
		}
	}
	//操作短信表
	public function save_sms($mobile='', $content='', $sms_id=0){
		if ($sms_id>0) {
			$sql = "UPDATE {$this->tbp}sms SET status=1 WHERE id='{$sms_id}'";
			$this->db->query($sql);
		} else {
			$sql = "INSERT INTO {$this->tbp}sms (mobile, content, ip, add_time, status) VALUES
				('{$mobile}', '{$content}', '{$this->ip}', '".time()."', '0')";
			$this->db->query($sql);
			return intval($this->db->insert_id);
		}
	}

	private function _menu(){
		$nav = $this->menu($this->admin_id);
		//echo json_encode($nav);exit;
		$this->smarty->assign('nav', $nav);
	}
	public function menu($admin_id){
		$sql = "SELECT * FROM {$this->tbp}admin_menu WHERE admin_id='{$admin_id}'";
		$menu = $this->db->get_results($sql);
		$sql = "SELECT * FROM {$this->tbp}gm_menu WHERE parent_id=0 AND status=1 ORDER BY sort ASC, id ASC";
		$first = $this->db->get_results($sql);
		$sql = "SELECT * FROM {$this->tbp}gm_menu WHERE parent_id>0 AND status=1 ORDER BY sort ASC, id ASC";
		$second = $this->db->get_results($sql);
		foreach ($first as $fk=>$f) {
			$nav = new stdClass();
			if ($admin_id==1) {
				$first[$fk]->checked = 'checked';
				foreach ($second as $sk=>$s) {
					$second[$sk]->checked = 'checked';
					if ($f->id == $s->parent_id) {
						$nav->$sk = $second[$sk];
					}
				}
				$first[$fk]->sub = $nav;
				continue;
			}
			if ($menu) {
				foreach ($menu as $mk=>$m) {
					//判断是否选中
					if ($m->menu_id == $f->id) {
						$first[$fk]->checked = 'checked';
					}
					foreach ($second as $sk=>$s) {
						//判断是否选中
						if ($m->menu_id == $s->id) {
							$second[$sk]->checked = 'checked';
						}
						if ($f->id == $s->parent_id) {
							$nav->$sk = $second[$sk];
						}
					}
				}
			} else {//如果都没有权限
				foreach ($second as $sk=>$s) {
					//判断是否选中
					if ($f->id == $s->parent_id) {
						$nav->$sk = $second[$sk];
					}
				}
			}
			$first[$fk]->sub = $nav;
		}
		return $first;
	}
	
	//设置分页的参数
	public function setpages($data=array()) {
		$BRSR = (isset($_GET['BRSR']) && trim($_GET['BRSR'])) ? trim($_GET['BRSR']) : '';
		$this->smarty->assign('BRSR', $BRSR);
		$this->ezr->set_qs_val('app', $this->app);
		$this->ezr->set_qs_val('act', $this->act);
		foreach ($data as $key=>$value) {
			$this->ezr->set_qs_val($key, $value);
			$this->smarty->assign($key, $value);
		}
	}

	//trigger error, exit
	public function error($msg, $msg_type=-1, $error=1) {
		error($msg, $msg_type, $error);
	}

	//日志
	private function _handle_log() {
		$log = m("log");
		$log->create();
	}
}
